package thread;

import lombok.Data;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * Fork/Join 框架
 * @author Duanyu
 * @date 2021-11-10 9:52
 */
public class ForkJoinPoolTest {


    @Test
    public void test() {

        ForkJoinPool pool = new ForkJoinPool();
        long timeMillis = System.currentTimeMillis();
        ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 10000000000L);
        System.out.println(pool.invoke(task)+":"+ (System.currentTimeMillis() - timeMillis));
    }

    @Test
    public void test2() {
        long timeMillis = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10000000000L).parallel().sum();
        System.out.println(sum+":"+ (System.currentTimeMillis() - timeMillis));
    }

}

class ForkJoinSumCalculate extends RecursiveTask<Long> {

    private final long start;

    private final long end;

    /** 临界值*/
    public static final long THRESHOLD = 10000L;

    public ForkJoinSumCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;

        if (length <= THRESHOLD) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;

        } else {
            long middle = (start + end) / 2;
            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
            //进行拆分,同时压入线程队列
            left.fork();

            ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
            //进行拆分,同时压入线程队列
            right.fork();

            return left.join() + right.join();
        }
    }
}
